/**
 * KidsMind 管理后台脚本
 */

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 自动关闭提示框
    const alerts = document.querySelectorAll('.alert-dismissible');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            const closeButton = alert.querySelector('.btn-close');
            if (closeButton) {
                closeButton.click();
            }
        }, 3000);
    });
    
    // 表格中的删除确认
    const deleteButtons = document.querySelectorAll('[data-action="delete"]');
    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            if (!confirm('确定要删除这条记录吗？此操作不可恢复。')) {
                e.preventDefault();
            }
        });
    });
    
    // 预览上传的图片
    const imageInputs = document.querySelectorAll('input[type="file"][data-preview]');
    imageInputs.forEach(function(input) {
        input.addEventListener('change', function() {
            const previewElement = document.getElementById(this.dataset.preview);
            if (previewElement && this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewElement.src = e.target.result;
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });
    
    // 统计图表初始化
    initCharts();
});

/**
 * 初始化统计图表
 */
function initCharts() {
    // 用户注册统计
    const userStatsCanvas = document.getElementById('userStatsChart');
    if (userStatsCanvas) {
        fetch('api.php?action=get_user_stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    new Chart(userStatsCanvas, {
                        type: 'line',
                        data: {
                            labels: data.dates,
                            datasets: [{
                                label: '新注册用户',
                                data: data.counts,
                                backgroundColor: 'rgba(13, 110, 253, 0.2)',
                                borderColor: 'rgba(13, 110, 253, 1)',
                                borderWidth: 2,
                                tension: 0.3
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        precision: 0
                                    }
                                }
                            }
                        }
                    });
                }
            })
            .catch(error => console.error('获取用户统计数据失败:', error));
    }
    
    // 游戏活跃度统计
    const gameStatsCanvas = document.getElementById('gameStatsChart');
    if (gameStatsCanvas) {
        fetch('api.php?action=get_game_stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    new Chart(gameStatsCanvas, {
                        type: 'bar',
                        data: {
                            labels: data.games,
                            datasets: [{
                                label: '游戏次数',
                                data: data.counts,
                                backgroundColor: 'rgba(25, 135, 84, 0.2)',
                                borderColor: 'rgba(25, 135, 84, 1)',
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        precision: 0
                                    }
                                }
                            }
                        }
                    });
                }
            })
            .catch(error => console.error('获取游戏统计数据失败:', error));
    }
    
    // 成就获取统计
    const achievementStatsCanvas = document.getElementById('achievementStatsChart');
    if (achievementStatsCanvas) {
        fetch('api.php?action=get_achievement_stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    new Chart(achievementStatsCanvas, {
                        type: 'pie',
                        data: {
                            labels: data.achievements,
                            datasets: [{
                                data: data.counts,
                                backgroundColor: [
                                    'rgba(13, 110, 253, 0.7)',
                                    'rgba(25, 135, 84, 0.7)',
                                    'rgba(220, 53, 69, 0.7)',
                                    'rgba(255, 193, 7, 0.7)',
                                    'rgba(111, 66, 193, 0.7)',
                                    'rgba(23, 162, 184, 0.7)'
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }
            })
            .catch(error => console.error('获取成就统计数据失败:', error));
    }
    
    // 年龄段分布统计
    const ageGroupCanvas = document.getElementById('ageGroupChart');
    if (ageGroupCanvas) {
        fetch('api.php?action=get_age_group_stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    new Chart(ageGroupCanvas, {
                        type: 'doughnut',
                        data: {
                            labels: data.groups,
                            datasets: [{
                                data: data.counts,
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.7)',
                                    'rgba(54, 162, 235, 0.7)',
                                    'rgba(255, 206, 86, 0.7)'
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }
            })
            .catch(error => console.error('获取年龄段统计数据失败:', error));
    }
} 